package sistema.usuario.dao;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.thoughtworks.xstream.XStream;

import util.CAoSFileReader;
import util.InvalidFileException;

/**
 * 
 * @author Autor desconhecido
 * @since 09/05/2006
 */
public class UsuarioFileReader implements CAoSFileReader{

	public Object processFile(String file) throws InvalidFileException {
		XStream xstream = new XStream();
		xstream.alias("Usuarios", HashMap.class);
        StringBuffer xmlFinal = null;
        BufferedReader textReader = null;
        try {
            textReader = new BufferedReader(new InputStreamReader(new FileInputStream(
                    file), "UTF-8"));
            String inputLine;
            while ((inputLine = textReader.readLine()) != null) {
                if (null == xmlFinal) {
                    xmlFinal = new StringBuffer(inputLine);
                } else {
                    xmlFinal.append(inputLine);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new InvalidFileException(e);
        } catch (FileNotFoundException e) {
            throw new InvalidFileException(e);
        } catch (IOException e) {
            throw new InvalidFileException(e);
        } finally {
            try {
                textReader.close();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
        Map usuarios = null;
        if (null != xmlFinal && !xmlFinal.toString().trim().equals("")) {
            try {
            	
            	usuarios = (HashMap) xstream.fromXML(xmlFinal
                        .toString());
            } catch (Exception e) {
            	//e.printStackTrace();
                throw new InvalidFileException("Arquivo <" + file
                        + "> em formato inv�lido.", e);
            }
        } else {
            throw new InvalidFileException("Arquivo <" + file
                    + "> vazio ou em formato inv�lido.");
        }

        return usuarios;
	}
	

}
